﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Runtime.Serialization;
using ClassLibrary1;
using System.Configuration;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace ClassLibrary3
{
    public class VersionableServiceHost : ServiceHost
    {
        IBusinessObjectSurrogate m_dataContractSurrogate = null;

        public VersionableServiceHost()
        {
            //GetSurrogate();
        }

        public VersionableServiceHost(Type serviceType, params Uri[] baseAddresses)
            : base(serviceType, baseAddresses)
        {
            //GetSurrogate();
        }

        private void GetSurrogate()
        {
            object section = ConfigurationManager.GetSection("unity");

            if (section != null)
            {
                IUnityContainer container = new UnityContainer();
                container.LoadConfiguration();

                m_dataContractSurrogate = container.Resolve<IBusinessObjectSurrogate>("UtenteSurrogate");
            }
        }

        //public VersionableServiceHost(IDataContractSurrogate dataContractSurrogate)
        //{
        //    m_dataContractSurrogate = dataContractSurrogate;
        //}

        protected override void ApplyConfiguration()
        {
            base.ApplyConfiguration();

            GetSurrogate();

            foreach (var endpoint in this.Description.Endpoints)
            {
                foreach (var operation in endpoint.Contract.Operations)
                {
                    operation.Behaviors.Find<DataContractSerializerOperationBehavior>().DataContractSurrogate = m_dataContractSurrogate;
                }
            }
        }
    }
}
